﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using GLIMS.DBUtility;
using System.Xml.Linq;
using System.Data.SqlClient;
using GLIMS.Common;
using System.ServiceModel.Channels;
using System.Collections.Specialized;
using System.Data;

namespace GLIMS.Common.GWF
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Form
    {
        public static string GetWhereText(string formCode, string optionCode)
        {
            var whereTexts = GWF.DsWorkFlow.Tables["gwf_Form"].Rows.OfType<DataRow>().Where(x => x["FormCode"].ToString() == formCode && x["OptionCode"].ToString() == optionCode)
                .Select(x=>x["WhereText"].ToString());
            if (whereTexts.Count() == 0) 
            {
                throw new Exception("配置的FormCode和OptionCode无法指定wheretext行");
            }
            return " AND (" + whereTexts.Aggregate((x, y) => string.Format("{0} OR {1}", x, y)) + ")"; 
        }

        public static string[] GetNodeCodes(string formCode, string optionCode) 
        {
            return GWF.DsWorkFlow.Tables["gwf_Form"].Rows.OfType<DataRow>().Where(x => x["FormCode"].ToString() == formCode && x["OptionCode"].ToString() == optionCode)
                .Select(x => x["NodeCode"].ToString()).ToArray();
        }

        [WebGet(UriTemplate = "/GetOptions?FormCode={formCode}")]
        public XElement GetOptions(string formCode) 
        {
            ResponseMessageInfo resInfo = new ResponseMessageInfo();

            resInfo.PopulateResponseData(new XElement("gwf_FormList", GWF.DsWorkFlow.Tables["gwf_Form"].Rows.OfType<DataRow>().Where(x => x["FormCode"].ToString() == formCode).Select(x =>
                    new XElement("gwf_Form", new XElement("OptionName", x["OptionName"]), new XElement("OptionCode", x["OptionCode"]), new XElement("NodeCode", x["NodeCode"])))
                    .Distinct(new XElementEqualityComparer("OptionCode")).OrderBy(x => x.Element("OptionCode").Value)
                    .ToArray()));
            return resInfo.DataRoot;    
        }
    }
}